package com.sangeng.service.impl;

import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sangeng.constant.enums.AppHttpCodeEnum;
import com.sangeng.constant.enums.CommentConstants;
import com.sangeng.domain.core.ResponseResult;
import com.sangeng.domain.dto.CommentListDto;
import com.sangeng.domain.entity.User;
import com.sangeng.domain.vo.CommentChildrenVo;
import com.sangeng.domain.vo.CommentVo;
import com.sangeng.domain.vo.PageVo;
import com.sangeng.exception.SystemException;
import com.sangeng.service.UserService;
import com.sangeng.utils.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sangeng.domain.entity.Comment;
import com.sangeng.mapper.CommentMapper;
import com.sangeng.service.CommentService;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 评论表(Comment)表服务实现类
 *
 * @author makejava
 * @since 2025-06-17 20:21:02
 */
@Service("commentService")
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Autowired
    private UserService userService;

    /**
     * 获取评论列表
     *
     * @param commentListDto
     * @return
     */
    @Override
    public ResponseResult commentList(CommentListDto commentListDto) {
        // 查询所有根评论
        Page<Comment> pageRequest = new Page<>(commentListDto.getPageNum(), commentListDto.getPageSize());
        LambdaQueryWrapper<Comment> queryWrapperRoot = new LambdaQueryWrapper<>();
        queryWrapperRoot.eq(Comment::getArticleId, commentListDto.getArticleId());
        // 判断是否是友链评论
        if(Objects.equals(commentListDto.getArticleId(), CommentConstants.LINK_ID)){
            // 是友链
            queryWrapperRoot.eq(Comment::getType, CommentConstants.COMMENT_TYPE_LINK)
                    .eq(Comment::getRootId, CommentConstants.ROOT_ID).
                    orderByDesc(Comment::getCreateTime);
        }
        else{
            // 不是友链
            queryWrapperRoot.eq(Comment::getRootId, CommentConstants.ROOT_ID).
                    orderByDesc(Comment::getCreateTime);
        }
        Page<Comment> page = page(pageRequest, queryWrapperRoot);
        List<Comment> comments = page.getRecords();
        if(comments.isEmpty()){
            return ResponseResult.okResult(new PageVo(comments, 0L));
        }
        // 将根评论封装给Vo
        List<CommentVo> records = BeanUtil.copyBeanList(comments, CommentVo.class);
        // 查询所有根评论的id并封装相应UserName至records中
        List<Long> parentRootIds = records.stream().map(CommentVo::getCreateBy).toList();
        LambdaQueryWrapper<User> queryWrapperParent = new LambdaQueryWrapper<>();
        queryWrapperParent.in(User::getId, parentRootIds);
        List<User> parentUsers = userService.list(queryWrapperParent);
        Map<Long, String> parentUserMap = parentUsers.stream().collect(Collectors.toMap(User::getId, User::getUserName));
        for(CommentVo commentVo : records){
            commentVo.setUsername(parentUserMap.get(commentVo.getCreateBy()));
        }

        // 查询所有子评论
        // 查询当前所有根评论的子评论
        List<Long> parentCommentIds = records.stream().map(CommentVo::getId).toList();
        LambdaQueryWrapper<Comment> queryWrapperChildren = new LambdaQueryWrapper<>();
        queryWrapperChildren.in(Comment::getRootId, parentCommentIds)
                .orderByDesc(Comment::getCreateTime);
        List<Comment> childrenComments = list(queryWrapperChildren);
        // 将子评论封装给Vo
        List<CommentChildrenVo> childrenCommentsVos = BeanUtil.copyBeanList(childrenComments, CommentChildrenVo.class);
        // 获取所有子评论的userName
        // 获取所有子评论的userId
        Set<Long> childrenUserIds = childrenComments.stream().map(Comment::getCreateBy).collect(Collectors.toSet());
        // 获取所有子评论的map：userId，userName
        if(!childrenUserIds.isEmpty()){
            Map<Long, String> userNameMapper = userService.listByIds(childrenUserIds).stream()
                    .collect(Collectors.toMap(
                            User::getId,       // Key: 用户ID
                            User::getUserName  // Value: 用户名
                    ));
            for (CommentChildrenVo childrenComment : childrenCommentsVos){
                if(parentUserMap.get(childrenComment.getToCommentUserId()) ==  null){
                    childrenComment.setToCommentUserName(userNameMapper.get(childrenComment.getToCommentUserId()));
                }
                else childrenComment.setToCommentUserName(parentUserMap.get(childrenComment.getToCommentUserId()));
                childrenComment.setUsername(userNameMapper.get(childrenComment.getCreateBy()));
            }
            Map<Long, List<CommentChildrenVo>> parentChildrenComments = childrenCommentsVos.stream()
                    .collect(Collectors.groupingBy(CommentChildrenVo::getRootId));

            //封装相应的子评论到父评论中
            for(CommentVo parentComment : records){
                parentComment.setChildren(parentChildrenComments.get(parentComment.getId()));
            }
        }
        PageVo pageVo = new PageVo(records, page.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    /**
     * 添加评论
     * @param comment
     * @return
     */
    @Override
    public ResponseResult addComment(Comment comment) {
        // 评论内容判断
        if (StringUtils.isBlank(comment.getContent())) {
            throw new SystemException(AppHttpCodeEnum.CONTENT_NOT_NULL);
        }
        // 将Dto转为Comment
        Comment addComment = BeanUtil.copyBean(comment, Comment.class);
        // 增加评论
        boolean save = save(addComment);
        if (!save) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
        }
        return ResponseResult.okResult();
    }
}

